<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorator="layout/default">
    <head lang="zh">
        <title>Hello Weibo</title>
    </head>
    <body>
        <div id="content" class="row" layout:fragment="content">
            <h2 class="indigo-text center" th:text="|#{resultPage.searchTitle}${keyword}|">keyword</h2>
            <div class="center">
                <div id="preloader" class="preloader-wrapper big active">
                    <div class="spinner-layer spinner-blue-only">
                        <div class="circle-clipper left">
                            <div class="circle"></div>
                        </div><div class="gap-patch">
                        <div class="circle"></div>
                    </div><div class="circle-clipper right">
                        <div class="circle"></div>
                    </div>
                    </div>
                </div>
            </div>
            <!--<ul id="weibos" class="collection">-->
                <!--li class="collection-item avatar" th:each="weibo:${weibos}">
                    <img th:src="${weibo.userImageUrl}" alt="" class="circle"/>
                    <span class="title" th:text="${weibo.userName}">Username</span>
                    <p th:text="${weibo.weibo}">Weibo</p>
                </li-->
            <!--</ul>-->
        </div>
        <script layout:fragment="script" th:inline="javascript">
            var baseUrl = [[@{/api/search}]];
            var currentLocation = window.location.href;
            var search = currentLocation.substr(currentLocation.lastIndexOf('/'));
            var url = baseUrl + search;

            /*$.ajax({
                url: url,
                type: "GET",
                beforeSend: setEtag,
                success: onResponse
            });*/

            function getLastQuery() {
                return JSON.parse(localStorage.getItem('lastQuery')) || {};
            }
            function storeQuery(query) {
                localStorage.setItem('lastQuery', JSON.stringify(query));
            }
            function setEtag(xhr) {
                xhr.setRequestHeader('If-None-Match', getLastQuery().etag);
            }
            function onResponse(weibos, status, xhr) {
                if(xhr.status == 304) {
                    console.log('304 not modified');
                    weibos = getLastQuery().weibos;
                }
                var etag = xhr.getResponseHeader('Etag');
                storeQuery({weibos:weibos,etag:etag});
                displayWeibos(weibos);
            }
            function displayWeibos(keyword,weibos) {
                $('#preloader').attr('style','');
                $('#'+keyword).empty();
                $.each(weibos, function(index, weibo) {
                    addWeibo(keyword,weibo);
                });
                setTimeout(() => $('#preloader').attr('style','display:none'), 500);
            }
            function addWeibo(keyword,weibo) {
                var template = _.template('<li class="collection-item avatar">' +
                    '<img src="${weibo.userImageUrl}" alt="" class="circle"/>' +
                    '<span class="title">${weibo.userName}</span>' +
                    '<p>${weibo.weibo}</p>' +
                    '</li>');
                $('#'+keyword).append(template({weibo:weibo}));
            }
            var searchArray = search.substr(search.lastIndexOf('=')+1).split(',');
            for(index in searchArray) {
                $('#content').append('<ul id="' + searchArray[index] + '" class="collection"></ul>');
            }

            var webSocket = new SockJS('localhost:8080/weiboSearch');
            var stompClient = Stomp.over(webSocket);
            // stompClient.debug = null;
            stompClient.connect({}, function(frame) {
                console.log('Connected: '+frame);
                for(index in searchArray) {
                    stompClient.subscribe('/topic/searchResults/' + searchArray[index], function(result) {
                        var returnData = JSON.parse(result.body);
                        displayWeibos(returnData.keyword, returnData.data);
                    });
                }
                stompClient.send('/app/search', {}, JSON.stringify(search.substr(search.lastIndexOf('=')+1).split(',')));
            });
        </script>
    </body>
</html>